#include "../include/db_manager.h"
#include <iostream>
#include <sstream>

DBManager* DBManager::instance = nullptr;

DBManager::DBManager() : connection(nullptr) {
}

//获取单例对象
DBManager& DBManager::getInstance() {
    if (instance == nullptr) {
        instance = new DBManager();
    }
    return *instance;
}

DBManager::~DBManager() {
    close();
}
//初始化数据库连接
bool DBManager::initialize(const std::string& host, const std::string& database, 
                          const std::string& username, const std::string& password) {
    connection = mysql_init(nullptr);
    if (!connection) {
        std::cerr << "MySQL初始化失败" << std::endl;
        return false;
    }
    
    // 设置字符集
    mysql_options(connection, MYSQL_SET_CHARSET_NAME, "utf8mb4");
    
    // 连接数据库
    if (!mysql_real_connect(connection, host.c_str(), username.c_str(), 
                           password.c_str(), database.c_str(), 0, nullptr, 0)) {
        std::cerr << "数据库连接失败: " << mysql_error(connection) << std::endl;
        return false;
    }
    
    std::cout << "数据库连接成功" << std::endl;
    return true;
}

bool DBManager::executeQuery(const std::string& query) {
    if (!connection) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    
    int result = mysql_query(connection, query.c_str());
    if (result != 0) {
        std::cerr << "查询执行失败: " << mysql_error(connection) << std::endl;
        return false;
    }

    return true;
}

//获取结果集
std::vector<std::map<std::string, std::string>> DBManager::executeSelectQuery(const std::string& query) {
    std::vector<std::map<std::string, std::string>> results;//结果集合
    
    if (!executeQuery(query)) {
        return results;
    }
    
    MYSQL_RES* result_set = mysql_store_result(connection);//结果集
    if (!result_set) {
        return results;
    }
    
    MYSQL_FIELD* fields = mysql_fetch_fields(result_set);//提取字段指针
    int num_fields = mysql_num_fields(result_set);
    //一个map(例子)组织了一个元组的字段信息
    //{
    //       name:lq
    //       password:word   
    //}
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result_set))) {
        std::map<std::string, std::string> row_data;//组织了一个元组的字段信息
        for (int i = 0; i < num_fields; i++) {
            std::string field_name = fields[i].name;//字段名
            std::string field_value = row[i] ? row[i] : "";//字段值
            row_data[field_name] = field_value;
        }
        results.push_back(row_data);//添加一个元组的数据
    }
    
    mysql_free_result(result_set);//释放缓冲区的结果集
    return results;
}

//获取最后的查询数据记录的那个ID(相对所有auto-increasement的ID字段)
unsigned long long DBManager::getLastInsertId() {
    return mysql_insert_id(connection);
}

//获取受影响的行数
unsigned long long DBManager::getAffectedRows() {
    return mysql_affected_rows(connection);
}

std::string DBManager::escapeString(const std::string& str) {
    if (!connection) return str;
    
    char* escaped = new char[str.length() * 2 + 1];
    mysql_real_escape_string(connection, escaped, str.c_str(), str.length());
    std::string result(escaped);
    delete[] escaped;
    return result;
}

void DBManager::close() {
    if (connection) {
        mysql_close(connection);
        connection = nullptr;
    }
}

bool DBManager::isConnected() const {
    return connection != nullptr;
} 